package durst.data.dao.impl;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import com.j256.ormlite.dao.BaseDaoImpl;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.DatabaseTableConfig;

import durst.data.Account;
import durst.data.CookieToAccount;
import durst.data.dao.DaoFactory;

public class CookieToAccountDao<T, ID> extends BaseDaoImpl<T, ID> {
	@SuppressWarnings("unchecked")
	public CookieToAccountDao(ConnectionSource connectionSource)
			throws SQLException {
		super(connectionSource, (Class<T>) CookieToAccount.class);
	}

	public CookieToAccountDao(ConnectionSource connectionSource,
			DatabaseTableConfig<T> tableConfig) throws SQLException {
		super(connectionSource, tableConfig);
	}

	@SuppressWarnings("unchecked")
	public Account findById(ID id, Date expires) throws SQLException {
		List<CookieToAccount> res = (List<CookieToAccount>)queryBuilder().where().eq(CookieToAccount.ID, id).and()
				.gt(CookieToAccount.EXPIRES, expires).query();

		assert (res.size() <= 1);

		Account ret = null;
		for (CookieToAccount cook : res) {
			Dao<Account, Integer> accDao = DaoFactory.getInstance().createDao(
					Account.class);
			accDao.refresh(cook.getAccount());
			ret = cook.getAccount();
		}

		return ret;
	}
}
